package de.dopichaj.labrador.search.erg;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
 * The Element Relationship Graph.
 * @author Benedikt
 */
public class ElementRelationshipGraph {

    /**
     * Scores for hits that are not found in any category are multiplied with
     * this value. Make sure that it is below any other coherence value in the
     * ElementRelationshipGraph.
     */
    static final double MINIMUM_COHERENCE_VALUE = 0.1;

    /**
     * A logger for this class
     */
    private static final Logger log = Logger.getLogger(ElementRelationshipGraph.class);

    private final Map<String, ErgNode> nodes = new HashMap<String, ErgNode>();
    private final List<String> allCategories = new ArrayList<String>();
    
    /**
     * Create an empty ERG.
     */
    public ElementRelationshipGraph() {
        log.info("Initializing ERG.");
    }
    
    public ElementRelationshipGraph(InputStream... streams) throws ErgFileFormatException, IOException {
        this();
        
        Validate.noNullElements(streams);
        
        for (InputStream stream : streams) {
            try {
                readErgFile(stream);
            } catch (ParserConfigurationException e) {
                throw new ErgFileFormatException(e);
            } catch (SAXException e) {
                throw new ErgFileFormatException(e);
            }
        }
    }

    private void readErgFile(InputStream stream) throws ParserConfigurationException, SAXException, IOException {
        
        // set up XML Parser
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setEntityResolver(new CatalogResolver());
        ErgDocumentHandler handler = new ErgDocumentHandler();
        xmlReader.setContentHandler(handler);
        
        xmlReader.parse(new InputSource(stream));
        SAXParseException e = handler.getException();
        if (e != null) {
            throw e;
        }
    }
    
    private final class ErgDocumentHandler extends DefaultHandler {

        private static final String TAG_ERG = "erg";
        private static final String TAG_TAG = "tag";
        private static final String TAG_CATEGORY = "category";
        
        private final Stack<ErgNode> nodeStack = new Stack<ErgNode>();
        private SAXParseException exception = null;
        private Locator locator;
        
        private void addChild(ErgNode child) {
            if (nodeStack.size() > 0) {
                ErgNode parent = nodeStack.peek();
                parent.addChild(child);
                child.addParent(parent);
            }
        }
        
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) {
            
            if (qName.equals(TAG_ERG)) {
                if (nodeStack.size() > 0) {
                    exception =
                        new SAXParseException("erg tag in wrong place", locator);
                }
            } else if (qName.equals(TAG_TAG)) {
                
                String name = attributes.getValue("name");
                ErgNode node = nodes.get(name);
                if (node == null) {
                    node = new ErgNode(name, ErgNode.Type.TAG, 1.0);
                    nodes.put(name, node);
                }
                addChild(node);
                nodeStack.push(node);
                
            } else if (qName.equals(TAG_CATEGORY)) {
                String name = attributes.getValue("name");
                ErgNode node;
                if (attributes.getValue("coherence") != null) {
                    double coherence =
                        Double.parseDouble(attributes.getValue("coherence"));
                    if (coherence <= MINIMUM_COHERENCE_VALUE) {
                        log.warn("Coherence of node <= minumum: " + coherence +
                            " <= " + MINIMUM_COHERENCE_VALUE);
                    }
                    if (nodes.containsKey(name)) {
                        log.warn("Coherence declared twice for " + name);
                        node = nodes.get(name);
                    } else {
                        node = new ErgNode(name, ErgNode.Type.CATEGORY, coherence);
                        nodes.put(name, node);
                        allCategories.add(name);
                    }
                } else {
                    node = nodes.get(name);
                }
                addChild(node);
                nodeStack.push(node);
            } else {
                exception =
                    new SAXParseException("Invalid tag name: " + qName, locator);
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) {
            if (qName.equals(TAG_TAG) || qName.equals(TAG_CATEGORY)) {
                nodeStack.pop();
            }
        }
        
        public SAXParseException getException() {
            return exception;
        }

        @Override
        public void setDocumentLocator(Locator locator) {
            this.locator = locator;
        }
    }

    public ErgNode lookupNode(String name) {
        
        Validate.notNull(name);
        
        if (nodes.containsKey(name)) {
            return nodes.get(name);
        } else {
            return new ErgNode(name, ErgNode.Type.TAG, 1.0);
        }
    }

    /**
     * Returns a default value that an unprocessed hit gets assigned.
     * Implemented as <code>score * RDF_MINIMUM_COHERENCE_VALUE</code>.
     */
    public double getScoreUnprocessedHit(double score) {
        
        Validate.isTrue(score >= 0);
        
        double retVal = score * MINIMUM_COHERENCE_VALUE;
        return retVal;
    }

    /**
     * Get all elements in the broader category, excluding those in the narrower
     * category. 
     * @param category A category.
     * @param broaderCategory broaderCategory
     * @return All descendant elements of the broader category, excluding
     *   the descendant elements of category.
     */
    public Set<ErgNode> getElementsInCategory(ErgNode broaderCategory,
            ErgNode category) {
        
        Validate.notNull(broaderCategory);
        Validate.notNull(category);
        
        Set<ErgNode> elementsInBroaderCategory = broaderCategory.getDescendants();
        Set<ErgNode> elementsInCategory = category.getDescendants();
        elementsInCategory.add(category);
        elementsInBroaderCategory.removeAll(elementsInCategory);
        return Collections.unmodifiableSet(elementsInBroaderCategory);
    }

}
/*
Copyright (c) 2005 Benedikt Eger
Copyright (c) 2005-2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/